// DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化主页功能
    initHomePageFunctions();
    
    // 侧边栏切换
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const overlay = document.getElementById('sidebarOverlay');

    if (sidebarToggle && sidebar && mainContent && overlay) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('sidebar-active');
            overlay.classList.toggle('hidden');
            document.body.classList.toggle('overflow-hidden');
        });

        overlay.addEventListener('click', function() {
            sidebar.classList.remove('sidebar-active');
            overlay.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
        });
    }

    // 搜索按钮点击事件
    const searchButton = document.getElementById('searchButton');
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');
    const loadingIndicator = document.getElementById('loadingIndicator');

    if (searchButton && searchInput) {
        searchButton.addEventListener('click', function() {
            searchMovies();
        });

        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchMovies();
            }
        });
    }

    // 搜索电影函数
    function searchMovies() {
        const keyword = searchInput.value.trim();
        if (!keyword) {
            alert('请输入搜索关键词');
            return;
        }

        // 显示加载状态
        if (loadingIndicator) {
            loadingIndicator.classList.remove('hidden');
        }
        if (searchResults) {
            searchResults.classList.add('hidden');
        }

        // 发送搜索请求
        fetch('/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ keyword: keyword })
        })
        .then(response => response.json())
        .then(data => {
            // 隐藏加载状态
            if (loadingIndicator) {
                loadingIndicator.classList.add('hidden');
            }

            // 显示搜索结果
            if (searchResults) {
                searchResults.classList.remove('hidden');
                renderSearchResults(data.results || []);
            }
        })
        .catch(error => {
            console.error('搜索失败:', error);
            if (loadingIndicator) {
                loadingIndicator.classList.add('hidden');
            }
            alert('搜索失败，请重试');
        });
    }

    // 渲染搜索结果
    function renderSearchResults(results) {
        if (!searchResults) return;

        if (results.length === 0) {
            searchResults.innerHTML = '<div class="text-center p-8 text-gray-500">未找到相关电影</div>';
            return;
        }

        let html = '<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">';
        results.forEach(movie => {
            html += `
                <div class="bg-white rounded-lg shadow-md overflow-hidden card-hover cursor-pointer" onclick="viewMovieDetail('${movie.id}')">
                    <div class="relative">
                        <img src="${movie.poster || '/static/images/placeholder.png'}" alt="${movie.title}" class="w-full h-48 object-cover">
                        <div class="absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
                            ${movie.rating || '暂无评分'}
                        </div>
                    </div>
                    <div class="p-3">
                        <h3 class="font-bold text-gray-800 line-clamp-1">${movie.title}</h3>
                        <p class="text-gray-500 text-sm line-clamp-1">${movie.year || '年份不详'}</p>
                    </div>
                </div>
            `;
        });
        html += '</div>';

        searchResults.innerHTML = html;
    }

    // 查看电影详情
    window.viewMovieDetail = function(movieId) {
        // 显示加载状态
        if (loadingIndicator) {
            loadingIndicator.classList.remove('hidden');
        }
        const movieDetail = document.getElementById('movieDetail');
        if (movieDetail) {
            movieDetail.classList.add('hidden');
        }

        // 发送获取详情请求
        fetch('/movie_detail', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ movie_id: movieId })
        })
        .then(response => response.json())
        .then(data => {
            // 隐藏加载状态
            if (loadingIndicator) {
                loadingIndicator.classList.add('hidden');
            }

            // 显示电影详情
            if (movieDetail) {
                movieDetail.classList.remove('hidden');
                renderMovieDetail(data);
            }

            // 滚动到详情区域
            if (movieDetail) {
                movieDetail.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        })
        .catch(error => {
            console.error('获取电影详情失败:', error);
            if (loadingIndicator) {
                loadingIndicator.classList.add('hidden');
            }
            alert('获取电影详情失败，请重试');
        });
    };

    // 渲染电影详情
    function renderMovieDetail(movie) {
        const movieDetail = document.getElementById('movieDetail');
        if (!movieDetail) return;

        // 处理演员数据
        const actors = movie.actors || [];
        const actorsHtml = actors.length > 0 ? 
            actors.map(actor => `<span class="inline-block bg-gray-100 rounded-full px-3 py-1 text-sm font-medium text-gray-700 mr-2 mb-2">${actor}</span>`).join('') : 
            '暂无演员信息';

        // 处理剧情简介
        const summary = movie.summary || '暂无剧情简介';

        // 处理标签
        const tags = movie.tags || [];
        const tagsHtml = tags.length > 0 ? 
            tags.map(tag => `<span class="inline-block bg-blue-100 text-blue-800 rounded-full px-3 py-1 text-xs font-medium mr-2 mb-2">${tag}</span>`).join('') : 
            '';

        // 填充详情HTML
        movieDetail.innerHTML = `
            <div class="bg-white rounded-lg shadow-lg p-6">
                <div class="flex flex-col md:flex-row gap-6">
                    <div class="md:w-1/4">
                        <img src="${movie.poster || '/static/images/placeholder.png'}" alt="${movie.title}" class="w-full h-auto rounded-md">
                    </div>
                    <div class="md:w-3/4">
                        <div class="flex justify-between items-start mb-4">
                            <div>
                                <h2 class="text-2xl font-bold text-gray-800">${movie.title}</h2>
                                <p class="text-gray-500">${movie.original_title || ''} (${movie.year || '年份不详'})</p>
                            </div>
                            <div class="bg-blue-500 text-white px-3 py-1 rounded-full font-semibold">
                                ${movie.rating || '暂无评分'}
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            ${tagsHtml}
                        </div>
                        
                        <div class="space-y-3 mb-6">
                            <p><span class="font-medium text-gray-700">导演：</span><span>${movie.director || '暂无导演信息'}</span></p>
                            <p><span class="font-medium text-gray-700">编剧：</span><span>${movie.screenwriter || '暂无编剧信息'}</span></p>
                            <p><span class="font-medium text-gray-700">类型：</span><span>${movie.genre || '暂无类型信息'}</span></p>
                            <p><span class="font-medium text-gray-700">制片国家/地区：</span><span>${movie.country || '暂无地区信息'}</span></p>
                            <p><span class="font-medium text-gray-700">语言：</span><span>${movie.language || '暂无语言信息'}</span></p>
                            <p><span class="font-medium text-gray-700">上映日期：</span><span>${movie.release_date || '暂无上映信息'}</span></p>
                            <p><span class="font-medium text-gray-700">片长：</span><span>${movie.runtime || '暂无片长信息'}</span></p>
                        </div>
                        
                        <div class="mb-6">
                            <h3 class="font-semibold text-gray-700 mb-2">剧情简介</h3>
                            <p class="text-gray-600 leading-relaxed">${summary}</p>
                        </div>
                        
                        <div class="mb-6">
                            <h3 class="font-semibold text-gray-700 mb-2">演员</h3>
                            <div class="flex flex-wrap">
                                ${actorsHtml}
                            </div>
                        </div>
                        
                        <div class="flex gap-3">
                            <button id="generateNfoBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md transition-colors">
                                生成NFO文件
                            </button>
                            <button id="backToSearchBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-2 rounded-md transition-colors">
                                返回搜索
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 绑定NFO生成按钮事件
        const generateNfoBtn = document.getElementById('generateNfoBtn');
        if (generateNfoBtn) {
            generateNfoBtn.addEventListener('click', function() {
                generateNfo(movie.id);
            });
        }

        // 绑定返回搜索按钮事件
        const backToSearchBtn = document.getElementById('backToSearchBtn');
        if (backToSearchBtn) {
            backToSearchBtn.addEventListener('click', function() {
                if (movieDetail) {
                    movieDetail.classList.add('hidden');
                }
                if (searchResults) {
                    searchResults.classList.remove('hidden');
                    searchResults.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            });
        }
    }

    // 生成NFO文件
    function generateNfo(movieId) {
        // 显示加载状态
        if (loadingIndicator) {
            loadingIndicator.classList.remove('hidden');
        }

        // 发送生成NFO请求
        fetch('/generate_nfo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ movie_id: movieId })
        })
        .then(response => {
            if (response.ok) {
                return response.blob();
            }
            throw new Error('生成NFO文件失败');
        })
        .then(blob => {
            // 隐藏加载状态
            if (loadingIndicator) {
                loadingIndicator.classList.add('hidden');
            }

            // 创建下载链接并触发下载
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${movieId}.nfo`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);

            alert('NFO文件生成成功，已开始下载');
        })
        .catch(error => {
            console.error('生成NFO文件失败:', error);
            if (loadingIndicator) {
                loadingIndicator.classList.add('hidden');
            }
            alert('生成NFO文件失败，请重试');
        });
    }

    // 滚动到顶部按钮功能
    const scrollToTopBtn = document.getElementById('scrollToTopBtn');
    if (scrollToTopBtn) {
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                scrollToTopBtn.classList.remove('hidden');
            } else {
                scrollToTopBtn.classList.add('hidden');
            }
        });

        scrollToTopBtn.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }

    // 主题切换功能
    const themeToggle = document.getElementById('themeToggle');
    if (themeToggle) {
        themeToggle.addEventListener('click', function() {
            document.documentElement.classList.toggle('dark');
            const isDark = document.documentElement.classList.contains('dark');
            localStorage.setItem('theme', isDark ? 'dark' : 'light');
        });
    }

    // 检查本地存储中的主题设置
    if (localStorage.getItem('theme') === 'dark' || 
        (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.classList.add('dark');
    } else {
        document.documentElement.classList.remove('dark');
    }
});

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

/**
 * 初始化主页功能
 */
function initHomePageFunctions() {
    // 检查是否需要显示配置提醒
    checkConfigStatus();
    
    // 执行状态检测
    performStatusChecks();
    
    // 获取资源统计数据
    refreshResourceStats();
}

/**
 * 刷新资源统计数据
 */
function refreshResourceStats() {
    // 发送请求获取资源统计数据
    fetch('/api/resources/stats')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取资源统计数据失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.data) {
                // 更新本地资源数量 - 确保显示数字而不是对象
                const localResourcesCount = typeof data.data.local_resources === 'object' ? 
                    (data.data.local_resources.count || 0) : 
                    (data.data.local_resources || 0);
                document.getElementById('local-resources-count').textContent = localResourcesCount;
                
                // 更新飞牛媒体库数量
                document.getElementById('fnos-libraries-count').textContent = 
                    (typeof data.data.fnos_media_libraries === 'object' ? 
                    (data.data.fnos_media_libraries.count || 0) : 
                    (data.data.fnos_media_libraries || 0));
                
                // 更新Emby媒体库数量
                document.getElementById('emby-libraries-count').textContent = 
                    (typeof data.data.emby_media_libraries === 'object' ? 
                    (data.data.emby_media_libraries.count || 0) : 
                    (data.data.emby_media_libraries || 0));
                
                // 更新qBittorrent任务数
                document.getElementById('qbittorrent-tasks-count').textContent = 
                    (typeof data.data.qbittorrent_tasks === 'object' ? 
                    (data.data.qbittorrent_tasks.count || 0) : 
                    (data.data.qbittorrent_tasks || 0));
                
                // 更新Transmission任务数
                document.getElementById('transmission-tasks-count').textContent = 
                    (typeof data.data.transmission_tasks === 'object' ? 
                    (data.data.transmission_tasks.count || 0) : 
                    (data.data.transmission_tasks || 0));
            }
        })
        .catch(error => {
            console.error('获取资源统计数据失败:', error);
        });
}

/**
 * 检查是否需要显示配置提醒
 */
function checkConfigStatus() {
    const reminderElement = document.getElementById('config-reminder');
    if (!reminderElement) return;
    
    // 直接从配置中读取状态
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data) {
                // 检查是否有有效的豆瓣cookie或PTSkit cookie
                const hasValidDoubanCookie = configData.data.douban && 
                                          configData.data.douban.cookie && 
                                          configData.data.douban.cookie.trim() !== '';
                
                const hasValidPTKitCookie = configData.data.ptskit && 
                                         configData.data.ptskit.cookie && 
                                         configData.data.ptskit.cookie.trim() !== '';
                
                // 如果两个cookie都没有配置，显示提醒
                if (!hasValidDoubanCookie && !hasValidPTKitCookie) {
                    reminderElement.classList.remove('hidden');
                }
            }
        })
        .catch(error => {
            console.error('获取配置失败:', error);
            // 如果获取配置失败，默认显示提醒
            reminderElement.classList.remove('hidden');
        });
}

/**
 * 检测其他刮削Cookie配置
 */
function checkOtherScrapeCookie() {
    const statusElement = document.getElementById('other-scrape-cookie-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 通过读取config.json判断是否有cookie值
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data && configData.data.javdb && configData.data.javdb.cookie) {
                // 检查cookie是否有效
                if (configData.data.javdb.cookie.trim() !== '') {
                    updateStatusElement(statusElement, 'success', 'Cookie已配置');
                } else {
                    updateStatusElement(statusElement, 'error', 'Cookie为空');
                }
            } else {
                updateStatusElement(statusElement, 'error', '未配置Cookie');
            }
        })
        .catch(error => {
            console.error('获取其他刮削配置失败:', error);
            updateStatusElement(statusElement, 'error', '配置读取失败');
        });
}

/**
 * 执行所有状态检测
 */
function performStatusChecks() {
    // 检测豆瓣连通性
    checkDoubanConnectivity();
    
    // 检测TMDB API连通性
    checkTmdbConnectivity();
    
    // 检测其他刮削Cookie配置
    checkOtherScrapeCookie();
    
    // 检测站点连通性
    checkPTKitConnectivity();
    
    // 检测本地资源映射
    checkLocalResourceMapping();
    
    // 其他模块初始化为未测试状态
    initUntestedModules();
    
    // 飞牛媒体库也初始化为未测试状态
    const statusElement = document.getElementById('fnos-media-connectivity-status');
    if (statusElement) {
        updateStatusElement(statusElement, 'untested', '未测试');
    }
}

/**
 * 初始化其他模块为未测试状态
 */
function initUntestedModules() {
    const untestedModules = [
        'tmdb-network-connectivity-status',
        'qbittorrent-connectivity-status',
        'transmission-connectivity-status',
        'emby-connectivity-status'
    ];
    
    untestedModules.forEach(id => {
        const statusElement = document.getElementById(id);
        if (statusElement) {
            updateStatusElement(statusElement, 'untested', '未测试');
        }
    });
}



/**
 * 检查Emby媒体服务器连通性
 */
function checkEmbyConnectivity() {
    const statusElement = document.getElementById('emby-connectivity-status');
    if (!statusElement) return;
    
    // 设置为检查中状态
    updateStatusElement(statusElement, 'info', '检查中...');
    
    // 通过调用API检查Emby媒体服务器的连通性
    fetch('/api/emby_media/check-connectivity')
        .then(response => {
            if (!response.ok) {
                throw new Error('连接检查失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                updateStatusElement(statusElement, 'success', '已连接');
            } else {
                updateStatusElement(statusElement, 'error', data.message || '未连接');
            }
        })
        .catch(error => {
            console.error('Emby媒体服务器连接检查失败:', error);
            updateStatusElement(statusElement, 'error', '连接检查失败');
        });
}

/**
 * 检查Plex媒体服务器连通性
 */
function checkPlexConnectivity() {
    const statusElement = document.getElementById('plex-connectivity-status');
    if (!statusElement) return;
    
    // 设置为检查中状态
    updateStatusElement(statusElement, 'info', '检查中...');
    
    // 简单实现，模拟连接检查
    // 实际应用中应该调用相应的API进行真实连接测试
    setTimeout(() => {
        updateStatusElement(statusElement, 'success', '已连接');
    }, 500);
}

/**
 * 检测qBittorrent连通性
 */
function checkQBittorrentConnectivity() {
    const statusElement = document.getElementById('qbittorrent-connectivity-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 通过config.json配置的信息检测连接下载器
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data && configData.data.qbittorrent) {
                const qbConfig = configData.data.qbittorrent;
                // 检查必要配置是否存在
                if (qbConfig.host && qbConfig.port && qbConfig.username) {
                    // 尝试连接下载器
                    fetch('/api/qbittorrent/test-connection', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(qbConfig)
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            if (data.data.is_connected) {
                                updateStatusElement(statusElement, 'success', '已连接');
                            } else {
                                updateStatusElement(statusElement, 'error', data.data.error || '连接失败');
                            }
                        } else {
                            updateStatusElement(statusElement, 'error', data.message || '连接失败');
                        }
                    })
                    .catch(error => {
                        console.error('qBittorrent连接测试失败:', error);
                        updateStatusElement(statusElement, 'error', '连接测试失败');
                    });
                } else {
                    updateStatusElement(statusElement, 'error', '配置不完整');
                }
            } else {
                updateStatusElement(statusElement, 'error', '未配置');
            }
        })
        .catch(error => {
            console.error('获取qBittorrent配置失败:', error);
            updateStatusElement(statusElement, 'error', '配置读取失败');
        });
}

/**
 * 检测Transmission连通性
 */
function checkTransmissionConnectivity() {
    const statusElement = document.getElementById('transmission-connectivity-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 通过config.json配置的信息检测连接下载器
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data && configData.data.transmission) {
                const trConfig = configData.data.transmission;
                // 检查必要配置是否存在
                if (trConfig.host && trConfig.port) {
                    // 尝试连接下载器
                    fetch('/api/transmission/test-connection', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(trConfig)
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            if (data.data && data.data.is_connected) {
                                updateStatusElement(statusElement, 'success', '已连接');
                            } else {
                                updateStatusElement(statusElement, 'error', data.data && data.data.error || '连接失败');
                            }
                        } else {
                            updateStatusElement(statusElement, 'error', data.message || '连接失败');
                        }
                    })
                    .catch(error => {
                        console.error('Transmission连接测试失败:', error);
                        updateStatusElement(statusElement, 'error', '连接测试失败');
                    });
                } else {
                    updateStatusElement(statusElement, 'error', '配置不完整');
                }
            } else {
                updateStatusElement(statusElement, 'error', '未配置');
            }
        })
        .catch(error => {
            console.error('获取Transmission配置失败:', error);
            updateStatusElement(statusElement, 'error', '配置读取失败');
        });
}

/**
 * 检测豆瓣连通性
 */
function checkDoubanConnectivity() {
    const statusElement = document.getElementById('douban-connectivity-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 通过读取config.json判断是否有cookie值
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data && configData.data.douban && configData.data.douban.cookie) {
                // 检查cookie是否有效
                if (configData.data.douban.cookie.trim() !== '') {
                    updateStatusElement(statusElement, 'success', 'Cookie已配置');
                } else {
                    updateStatusElement(statusElement, 'error', 'Cookie为空');
                }
            } else {
                updateStatusElement(statusElement, 'error', '未配置Cookie');
            }
        })
        .catch(error => {
            console.error('获取豆瓣配置失败:', error);
            updateStatusElement(statusElement, 'error', '配置读取失败');
        });
}

/**
 * 检测所有组件连通性
 */
function checkAllConnectivity() {
    // 依次检测所有组件
    checkDoubanConnectivity();
    checkTmdbConnectivity();
    checkOtherScrapeCookie();
    checkTmdbNetworkConnectivity();
    checkPTKitConnectivity();
    checkLocalResourceMapping();
    checkQBittorrentConnectivity();
    checkTransmissionConnectivity();
    checkEmbyConnectivity();
    testFnosMediaConnection();
}

/**
 * 检测PTKit站点连通性
 */
function checkPTKitConnectivity() {
    const statusElement = document.getElementById('ptskit-connectivity-status');
    if (!statusElement) return;
    
    // 通过读取config.json判断是否有cookie值
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data && configData.data.ptskit && configData.data.ptskit.cookie) {
                // 检查cookie是否有效
                if (configData.data.ptskit.cookie.trim() !== '') {
                    updateStatusElement(statusElement, 'success', 'Cookie已配置');
                } else {
                    updateStatusElement(statusElement, 'error', 'Cookie为空');
                }
            } else {
                updateStatusElement(statusElement, 'error', '未配置Cookie');
            }
        })
        .catch(error => {
            console.error('获取站点配置失败:', error);
            updateStatusElement(statusElement, 'error', '配置读取失败');
        });
}

/**
 * 检测飞牛媒体库连接状态
 */
function testFnosMediaConnection() {
    const statusElement = document.getElementById('fnos-media-connectivity-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    fetch('/api/fnos_media/test-connection')
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          updateStatusElement(statusElement, 'success', '已连接');
        } else {
          updateStatusElement(statusElement, 'error', '未连接');
        }
      })
      .catch(error => {
        console.error('测试飞牛媒体库连接失败:', error);
        updateStatusElement(statusElement, 'error', '连接失败');
      });
}

/**
 * 检测本地资源映射
 */
function checkLocalResourceMapping() {
    const statusElement = document.getElementById('local-resource-mapping-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 检测是否挂载了 /app/skit 目录
    fetch('/api/local-resources/check-mount')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data && data.data.is_mounted) {
                updateStatusElement(statusElement, 'success', '已挂载');
            } else {
                updateStatusElement(statusElement, 'error', data.message || '未挂载');
            }
        })
        .catch(error => {
            console.error('本地资源映射检测失败:', error);
            updateStatusElement(statusElement, 'error', '检测失败');
        });
}

/**
 * 检测TMDB API配置
 */
function checkTmdbConnectivity() {
    const statusElement = document.getElementById('tmdb-connectivity-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 通过读取config.json判断是否有API密钥配置
    fetch('/api/config/get')
        .then(response => response.json())
        .then(configData => {
            if (configData.success && configData.data && configData.data.tmdb && configData.data.tmdb.api_key) {
                // 检查API密钥是否有效
                if (configData.data.tmdb.api_key.trim() !== '') {
                    updateStatusElement(statusElement, 'success', 'API已配置');
                } else {
                    updateStatusElement(statusElement, 'error', 'API密钥为空');
                }
            } else {
                updateStatusElement(statusElement, 'error', '未配置API密钥');
            }
        })
        .catch(error => {
            console.error('获取TMDB配置失败:', error);
            updateStatusElement(statusElement, 'error', '配置读取失败');
        });
}

/**
 * 检测TMDB网络连通性
 */
function checkTmdbNetworkConnectivity() {
    const statusElement = document.getElementById('tmdb-network-connectivity-status');
    if (!statusElement) return;
    
    // 设置检查中状态
    updateStatusElement(statusElement, 'info', '检测中...');
    
    // 调用API检查TMDB连接状态
    fetch('/api/tmdb/check-connectivity')
        .then(response => {
            if (!response.ok) {
                throw new Error('连接检查失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                updateStatusElement(statusElement, 'success', '已连接');
            } else {
                updateStatusElement(statusElement, 'error', data.message || '未连接');
            }
        })
        .catch(error => {
            console.error('TMDB网络连接检查失败:', error);
            updateStatusElement(statusElement, 'error', '连接检查失败');
        });
}

/**
 * 更新状态显示元素
 * @param {HTMLElement} element - 状态元素
 * @param {string} status - 状态类型 (success, error, warning, info, untested)
 * @param {string} text - 状态文本
 */
function updateStatusElement(element, status, text) {
    // 移除所有状态类
    element.querySelector('span:last-child').className = '';
    
    // 根据状态设置不同的图标和颜色
    let iconClass = '';
    let textClass = '';
    
    switch (status) {
        case 'success':
            iconClass = 'fa-check-circle text-green-500';
            textClass = 'text-green-600';
            break;
        case 'error':
            iconClass = 'fa-times-circle text-red-500';
            textClass = 'text-red-600';
            break;
        case 'warning':
            iconClass = 'fa-exclamation-triangle text-amber-500';
            textClass = 'text-amber-600';
            break;
        case 'info':
            iconClass = 'fa-info-circle text-blue-500';
            textClass = 'text-blue-600';
            break;
        case 'untested':
            iconClass = 'fa-question-circle text-gray-500';
            textClass = 'text-gray-600';
            break;
        default:
            iconClass = 'fa-info-circle text-gray-500';
            textClass = 'text-gray-600';
    }
    
    // 更新元素内容
    element.querySelector('span:last-child').innerHTML = 
        `<i class="fa ${iconClass} mr-1"></i> <span class="${textClass}">${text}</span>`;
}

/**
 * 显示通知
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型 (success, error, info, warning)
 */
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type} fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full`;
    
    // 设置通知内容
    let iconClass = '';
    switch (type) {
        case 'success':
            iconClass = 'fa-check-circle';
            break;
        case 'error':
            iconClass = 'fa-times-circle';
            break;
        case 'warning':
            iconClass = 'fa-exclamation-triangle';
            break;
        default:
            iconClass = 'fa-info-circle';
    }
    
    notification.innerHTML = `
        <div class="flex items-center">
            <i class="fa ${iconClass} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}